package com.push.xu.xpush.client;


import android.app.Application;
import android.content.Context;
import android.os.Handler;

import com.push.xu.xpush.constant.Constant;
import com.push.xu.xpush.core.ZPushClient;
import com.push.xu.xpush.util.SPUtils;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

public class JPushClient implements ZPushClient {
	private Context context;

    private HashSet<String> tagSet = new HashSet<String>();

    private Handler handler = new Handler();

    private Runnable setTagRunnable = new Runnable() {
        @Override
        public void run() {
            JPushInterface.addTags(context, Constant.TYPE_ADD_TAG, (Set<String>) tagSet.clone());
            tagSet.clear();
        }
    };

    @Override
    public void initContext(Application application) {
        this.context = application.getApplicationContext();
        try {
        	JPushInterface.init(context);
		} catch (Exception e) {
			JPushInterface.stopPush(context);
		}
    }

    @Override
    public void register() {
        if (JPushInterface.isPushStopped(this.context)) {
            JPushInterface.resumePush(this.context);
        }
        String token = JPushInterface.getRegistrationID(context);
        SPUtils.getInstance(Constant.PUSH_MESSAGE_TABLE).put("push_token", token);
    }

    @Override
    public void unRegister() {
        JPushInterface.stopPush(this.context);
    }

	@Override
	public void clearNotiById(Context context, int id) {
		JPushInterface.clearNotificationById(context, id);
	}

	@Override
	public String getRegistration(Context context) {
		return JPushInterface.getRegistrationID(context).trim();
	}

    @Override
    public void bindAlias(String alias) {
        JPushInterface.setAlias(this.context, Constant.TYPE_BIND_ALIAS, alias);
    }

    @Override
    public void unBindAlias(String alias) {
        JPushInterface.deleteAlias(this.context, Constant.TYPE_UNBIND_ALIAS);
    }

    @Override
    public void addTag(String tag) {
        handler.removeCallbacks(setTagRunnable);
        tagSet.add(tag);
        handler.postDelayed(setTagRunnable, 300);
    }

    @Override
    public void deleteTag(String tag) {
        JPushInterface.deleteTags(this.context, Constant.TYPE_DEL_TAG, Collections.singleton(tag));
    }

}
